<template>
    <div>
        <div>
            <el-space style="margin-bottom: 10px">
                <span>选择模版：</span>
                <el-select
                    v-model="value"
                    class="m-2"
                    placeholder="选择模版"
                    size="small"
                    style="width: 240px"
                    @change="mobanpeihuan"
                >
                    <el-option
                        v-for="item in mobanArr"
                        :key="item.id"
                        :label="item.name?item.name:item.id"
                        :value="item.id"
                    />
                </el-select>
                <el-button :size="style.size" type="success" @click="addMban">新增模版</el-button>
                <el-button-group>
                    <el-button v-for="(value,type) in paperTypes" :type="curPaperType === type ? 'primary' : ''"
                        @click="setPaper(type,value)" :key="type" :size="style.size">
                        {{ type }}
                    </el-button>
                   <el-popover :visible="visible" placement="top" :width="260">
                        <div style="text-align: right; margin: 0">
                            <el-input type="number" :size="style.size" v-model="paperWidth" style=" width: 100px; text-align: center"
                            placeholder="宽(mm)"/>
                            <el-input :size="style.size" style=" width: 30px; border-left: 0; pointer-events: none; backgroundColor: #fff"
                                    placeholder="~" disabled
                            />
                            <el-input :size="style.size" type="number" v-model="paperHeight" style="width: 100px; text-align: center; border-left: 0"
                                    placeholder="高(mm)"/>
                        </div>
                        <div style="text-align: center; margin: 10px 0 0 0 ">
                            <el-button :size="style.size" style="width: 100%;" @click="otherPaper">确定</el-button>
                        </div>
                        <template #reference>
                            <el-button @click="visible = true" :size="style.size" :type="curPaperType === 'other' ? 'primary' : ''">自定义纸张</el-button>
                        </template>
                    </el-popover>
                </el-button-group>
                 <el-button :size="style.size" type="success" :icon="ZoomOut" @click="changeScale(false)"></el-button>
                <el-input :size="style.size" style="width: 70px;" v-show="true" :value="`${(scaleValue * 100).toFixed(0)}%`" disabled />
                <el-button :size="style.size" type="success" :icon="ZoomIn" @click="changeScale(true)"></el-button>
                <el-button :size="style.size" type="success" :icon="View" @click="preView">预览</el-button>
                <el-button :size="style.size" type="primary" :icon="Printer" @click="print">打印</el-button>
                <el-button :size="style.size" type="primary" :icon="Printer" @click="save">保存</el-button>
            </el-space>
        </div>
        <div>
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-card style="overflow: auto;height: 100vh;">
                        <el-row>
                            <el-col :span="24" class="rect-printElement-types hiprintEpContainer">
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
                <el-col :span="15">
                    <el-card class="card-design">
                        <div id="hiprint-printTemplate" class="hiprint-printTemplate"></div>
                    </el-card>
                </el-col>
                <el-col :span="5" class="params_setting_container">
                    <el-card class="card-design">
                        <el-row class="hinnn-layout-sider">
                            <div id="PrintElementOptionSetting"></div>
                        </el-row>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <!-- 预览 -->
        <printPreview ref="preViewRef"/>
    </div>
</template>
<script setup>
    import {ref, computed,onMounted,watch} from "vue"
    import { ElMessage , ElMessageBox} from 'element-plus'
    import { ZoomOut, ZoomIn, View, Printer } from '@element-plus/icons-vue'
    import {hiprint,hiPrintPlugin} from 'vue-plugin-hiprint'
    import printPreview from './preview.vue'
    import {aProvider} from './providers.js'
    import XEUtils from "xe-utils"
    import { getPrintList, getPrinData, editPrint } from "/@/api/linkoo/print";
    const props = defineProps({
        tableData:{
            type:Array,
            required: true
        },
        sid:{
            type:Number||String
        }
    })
    let visible = ref(false)
    let preViewRef = ref(null)
    let arr = ref({})//测试展示数据
    let hiprintTemplate = ref(null);
    let paperWidth = ref('220')//自定义纸张宽
    let paperHeight = ref('80')//自定义纸张高
    let scaleValue = ref(1)//百分比
    let daitizhi = ref('100%')
    let scaleMax = ref(5)//百分比最大值
    let scaleMin = ref(0.5)//百分比最小值
    let formTop = ref(null)//表头设计
    let tableButtom = ref(null)//明细表设计
    let mobanArr = ref([])
    let mobanisData = ref(null) // 当前模版数据
    let value = ref(null)
    // 统一样式
    let style = ref({
        size:"small"
    })
    // 纸张类型
    let curPaper = ref({
        type: 'A4',
        width: 210,
        height: 296.6
    })
    // 计算属性，A4纸按钮高亮控制
    let curPaperType = computed(() => {
        let type = 'other'
        let types = paperTypes.value
        for (const key in types) {
            let item = types[key]
            let { width, height } = curPaper.value
            if (item.width === width && item.height === height) {
                type = key
            }
        }
        return type
    })
    // 字张设置
    const paperTypes = ref({
        'A3': {
            width: 420,
            height: 296.6
        },
        'A4': {
            width: 210,
            height: 296.6
        },
        'A5': {
            width: 210,
            height: 147.6
        },
        'B3': {
            width: 500,
            height: 352.6
        },
        'B4': {
            width: 250,
            height: 352.6
        },
        'B5': {
            width: 250,
            height: 175.6
        }
    })
    let templateList = ref(null)
    onMounted(async () => {
        
    })
    watch(()=>{ return props.tableData},()=>{
        datalist()
        getPrintList({ tid: props.sid }).then((res) => {
            mobanArr.value = res.data.list
        })
    })
    // 新增模版
    const addMban = ()=>{
        ElMessageBox.prompt('请输入模版名称', '新增模版', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
        }).then(({ value }) => {
                mobanArr.value.push({
                    name:value,
                    data:null
                })
                mobanisData.value=value
                arr.value={}
                ElMessage({
                    type: 'success',
                    message: `新增${value}`,
                })
                init()
                
            })
    }
    // 模版切换
    const mobanpeihuan = (value)=>{
        console.log(value);
        mobanArr.value.forEach((item,index)=>{
            if(value==item.id){
                arr.value=item.contento?JSON.parse(item.contento):{}
                if(hiprintTemplate.value){
                    hiprintTemplate.value.update(arr.value)
                }else{
                    init()
                }
            }
        })
    }
    let tablefilstData = ref([])
    // 侧边按钮数据
    const datalist = () => {
        console.log(props.tableData);
        let topList = []
        let buotmList = []
        let tablefilet = []
        topList.push({ tid: 'aProviderModule.logo', title: 'Logo', data: '', type: 'image' },)
        props.tableData.forEach(element => {
            if (element.tableType === 0) {
                element.Fields.forEach((item, index) => {
                    topList.push({
                        tid: item.fieldID, title: item.fieldTitle, data: item.fieldTitle, type: 'text',
                        options: {
                            field: item.fieldName,
                            testData: '测试数据' + index,
                            height: 16,
                            fontSize: 6.75,
                            fontWeight: "700",
                            textAlign: "left",
                            textContentVerticalAlign: "middle"
                        }
                    })
                })
            }else{
                console.log(element);
                let FieldsT = []
                let FieldsC = []
                element.Fields.forEach((item,index)=>{
                    FieldsT.push({ text: item.fieldTitle, field: item.fieldName })
                    FieldsC.push({ title: item.fieldTitle, align: 'center', field: item.fieldName, width: 150 })
                    tablefilet.push({
                        tid: item.fieldID, title: item.fieldTitle, data: item.fieldTitle, type: 'text',
                        options: {
                            field: item.fieldName,
                            testData: '测试数据' + index,
                            height: 16,
                            fontSize: 6.75,
                            fontWeight: "700",
                            textAlign: "left",
                            textContentVerticalAlign: "middle"
                        }
                    })
                })
                buotmList.push({
                    tid: 'T'+element.tableID, 
                    title: element.tableTitle,
                    type: 'table',
                    options: {
						field: element.tableName,
						tableHeaderRepeat: 'first',
						tableFooterRepeat: 'last',
						fields: FieldsT,
					},
                    editable: true,
					columnDisplayEditable: true,//列显示是否能编辑
					columnDisplayIndexEditable: true,//列顺序显示是否能编辑
					columnTitleEditable: true,//列标题是否能编辑
					columnResizable: true, //列宽是否能调整
					columnAlignEditable: true,//列对齐是否调整
					isEnableEditField: true, //编辑字段
					isEnableContextMenu: true, //开启右键菜单 默认true
					isEnableInsertRow: true, //插入行
					isEnableDeleteRow: true, //删除行
					isEnableInsertColumn: true, //插入列
					isEnableDeleteColumn: true, //删除列
					isEnableMergeCell: true, //合并单元格
                    columns: [FieldsC],
                })
                
            }
        });
        formTop.value = topList
        tableButtom.value= buotmList
        tablefilstData.value = tablefilet
        console.log(tablefilstData);
        // init()
    }
    let modeList = ref(null)
    // 组件初始化
    
    const init = () => {
        console.log(formTop.value);
        hiprint.init({
            providers: [aProvider(formTop.value,tableButtom.value,tablefilstData.value)]
        });
        $('.hiprintEpContainer').empty()
        hiprint.PrintElementTypeManager.build('.hiprintEpContainer', 'taskProviderModule');
        // 还原配置
        hiprint.setConfig()
        // 替换配置
        hiprint.setConfig({
            movingDistance: 2.5,
            text: {
                supportOptions: [
                    {
                        name: 'styler',
                        hidden: true
                    },
                    {
                        name: 'formatter',
                        hidden: true
                    },
                ]
            }
        })
        // eslint-disable-next-line no-undef
        hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
        hiprintTemplate.value = new hiprint.PrintTemplate({
            template: arr.value,
            settingContainer: '#PrintElementOptionSetting',
            paginationContainer: '.hiprint-printPagination'
        });
        hiprintTemplate.value.design('#hiprint-printTemplate');
        console.log(hiprintTemplate, arr.value);
        // 获取当前放大比例, 当zoom时传true 才会有
        scaleValue.value = hiprintTemplate.value.editingPanel.scale || 1;
    }
    const setPaper = (type, value) => {
        console.log(Object.keys(paperTypes.value).includes(type),type, value);
        
            if (Object.keys(paperTypes.value).includes(type)) {
                curPaper.value = { type: type, width: value.width, height: value.height }
                hiprintTemplate.value.setPaper(value.width, value.height)
            } else {
                curPaper.value = { type: 'other', width: value.width, height: value.height }
                hiprintTemplate.value.setPaper(value.width, value.height)
            }
       
    }
    // 视图百分比
    const changeScale = (big) => {
        let scaleValuet = scaleValue.value;
        if (big) {
            scaleValuet += 0.1;
            if (scaleValuet > scaleMax.value) scaleValuet = 5;
        } else {
            scaleValuet -= 0.1;
            if (scaleValuet < scaleMin.value) scaleValuet = 0.5;
        }
        if (hiprintTemplate.value) {
            // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
            scaleValue.value = scaleValuet;
            hiprintTemplate.value.zoom(scaleValue.value);
        }
    }
    const print = () => {
        hiprintTemplate.value.print({}, {}, {
            callback: () => {
                console.log('callback')
            }
        })
    }
    const otherPaper=()=> {
      let value = {}
      value['width'] = paperWidth.value
      value['height'] = paperHeight.value
      visible.value = false
      setPaper('other', value)
    }
    const preView=()=> {
      let {width} = curPaper.value
      console.log(preViewRef.value);
      preViewRef.value?.itfo(hiprintTemplate.value, {}, width)
    }
    const save = ()=>{
        let data = hiprintTemplate.value.historyList
        if(data.length==1){
            ElMessage({
                        type: 'error',
                        message: `无更改`,
                    })
        }else{
            mobanArr.value.forEach((item,index)=>{
                console.log(mobanisData.value==item.id,mobanisData.value,item.id);
                if(value.value==item.id){
                    let rtData = item
                    rtData.contento=JSON.stringify(hiprintTemplate.value.getJson()) 
                    editPrint(rtData).then((res) => {
                        ElMessage({
                            type: 'success',
                            message: "保存成功",
                        })
                    })
                }
            })
            // mobanisData.value.contento = JSON.stringify(hiprintTemplate.value.getJson()) 
            // console.log(JSON.stringify(hiprintTemplate.value.getJson()) );
        }
    }
</script>
<style lang="scss" scoped>
    /* // 拖拽 */
    .drag_item_box {
        height: 100%;
        padding: 6px;
    }

    .drag_item_box>div {
        height: 100%;
        width: 100%;
        background-color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .drag_item_box>div>a {
        text-align: center;
        text-decoration-line: none;
    }

    .drag_item_box>div>a>span {
        font-size: 28px;
    }

    .drag_item_box>div>a>p {
        margin: 0;
    }

    .drag_item_title {
        font-size: 16px;
        padding: 12px 6px 0 6px;
        font-weight: bold;
    }

    /* // 默认图片 */
    :deep(.hiprint-printElement-image-content) {
        img {
            content: url("~@/assets/logo.png");
        }
    }

    /* // 设计容器 */
    .card-design {
        overflow: hidden;
        overflow-x: auto;
        overflow-y: auto;
    }
    .rect-printElement-types > li > ul > li > .ep-draggable-item {
        height: auto !important;
    }
</style>